package com.csaba.connector.otp;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.htmlparser.jericho.Attribute;
import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.Source;

import com.csaba.connector.ServiceException;
import com.csaba.connector.otp.model.OTPRequestFactory;
import com.csaba.connector.otp.model.OTPSession;
import com.csaba.util.LoggerHelper;

public class WorkflowPolling
{
	private final static Logger logger = LoggerHelper.getDefaultLogger();

	public static final int POLL_LIMIT = 30;
	public static final int POLL_PERIOD = 1000;

	private static final Pattern WORKFLOW_EXTRACT = Pattern
			.compile(".*wfId[ =]+\"([^\"]+)\".*wfName[ =]+\"([^\"]+)\".*formId[: ]+\"([^\"]+)\".*");

	private static final String POLL_INDICATOR = "new WorkflowPoller";
	private static final String POLL_RESULT_FINISHED = "{\"folyamatAllapot\":\"FINISHED\"}";
	private static final String POLL_WAITING = "{\"folyamatAllapot\":\"WAITING\"}";

	private final OTPSession session;
	private final String URL;

	public WorkflowPolling( final OTPSession session, final String URL )
	{
		this.session = session;
		this.URL = URL;
	}

	public boolean poll() throws ServiceException
	{
		int pollCount = 0;
		for ( String poll = POLL_WAITING; !POLL_RESULT_FINISHED.equals(poll) && pollCount < POLL_LIMIT; pollCount++ )
		{
			try
			{
				Thread.sleep(POLL_PERIOD);
			}
			catch ( final InterruptedException ex )
			{
				logger.finest("Sleep was interrupted.");
			}

			poll = session.doGet(OTPRequestFactory.HOMEBANK_REQUEST_URL_BASE + URL);
			logger.fine("Poll[" + pollCount + "]:" + poll);
		}

		return pollCount < POLL_LIMIT;

	}

	public static String parsePollTransaction( final String source ) throws ServiceException
	{
		return parsePollTransaction(new Source(source));
	}

	public static String parsePollTransaction( final Source source ) throws ServiceException
	{
		String jsWorkflowInst = null;
		Element element = source.getNextElement(0, "script");
		while ( element != null )
		{
			final Attribute srcAttr = element.getAttributes().get("src");
			if ( srcAttr == null )
			{
				final String jsContent = element.getContent().toString();
				if ( jsContent.contains(POLL_INDICATOR) )
				{
					jsWorkflowInst = jsContent;
					break;
				}
			}
			element = source.getNextElement(element.getEnd(), "script");
		}

		/*
		var wfId = "000;434131250;10.42.2.125";
		var wfName = "000";
		
		$(document).ready(function(){

			$("#popup_bg").show();
			$("body").attr("id", "all_disabled");

			var wfPoller = new WorkflowPoller({
				delay: 5000,
				workflow: wfName,
				folyamatId: wfId,
				formId: "varakozasForm"
			});

			if(console) {
				console.debug("WorkflowPoller object created: ", wfPoller);
			}
			
			wfPoller.start();

		});
		 */
		//get IDs

		jsWorkflowInst = jsWorkflowInst.replace('\n', ' ');

		final Matcher matcher = WORKFLOW_EXTRACT.matcher(jsWorkflowInst);
		String url = null;
		if ( matcher.find() )
		{
			try
			{
				final StringBuilder urlBuilder = new StringBuilder();
				urlBuilder.append(OTPRequestFactory.REQUEST_POLL_TRANSACTION_ANSWER);
				urlBuilder.append("?contentType=JSON&folyamatId=");
				urlBuilder.append(URLEncoder.encode(matcher.group(1), "UTF-8"));
				urlBuilder.append("&workflow=").append(URLEncoder.encode(matcher.group(2), "UTF-8"));
				url = urlBuilder.toString();
				//final String formId = matcher.group(3);
			}
			catch ( final UnsupportedEncodingException e )
			{
				logger.log(Level.SEVERE, "Failed to construct polling URL.", e);
			}
		}

		return url;
	}

}
